import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
import { observable, computed } from 'mobx';

type F<S> = (p: S) => JSX.Element;
export const TodoList = observer<F<{ initialTodos: string[] }>>(
    ({ initialTodos }) => {
        const todoRef = React.useRef<HTMLInputElement>()

        class TodoStore {
            @observable todos: Record<string, boolean> = {}
            constructor(todolist: string[], private todoRef: React.MutableRefObject<HTMLInputElement>) {
                for (let t of todolist)
                    this.todos[t] = false;
            }

            @computed get pendingTodos() {
                return Object.keys(this.todos).filter(todo => this.todos[todo] === false)
            }

            @computed get doneTodos() {
                return Object.keys(this.todos).filter(todo => this.todos[todo] === true)
            }

            addTodo = (e: React.FormEvent<HTMLFormElement>) => {
                e.preventDefault();
                this.todos[this.todoRef.current.value] = false
                this.todoRef.current.value = ''
            }
            toggleTodo = (todo: string) => {
                this.todos[todo] = !this.todos[todo]
            }
        }

        const store = useLocalStore(() => new TodoStore(initialTodos, todoRef))
        const renderTodo = (done: boolean) => (todo: string) => (
            <div key={todo} onClick={() => { store.toggleTodo(todo) }} >{done ? "ok" : "no"} {todo}</div>
        )

        return (
            <form onSubmit={store.addTodo}>
                {store.pendingTodos.map(renderTodo(false))}
                {store.doneTodos.map(renderTodo(true))}
                <br />
                <input ref={todoRef} />
                <button>Add todo</button>
            </form>
        )
    }
)

export function RenderTodo_ClassStore() {
    ReactDOM.render(
        <TodoList
            initialTodos={['Introduce MobX in React', 'Make a great app with MobX']}
        />,
        document.getElementById("app"))
}
